package com.example.server.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.common.pojo.AdminRole;
import com.example.server.mapper.AdminRoleMapper;
import com.example.server.service.IAdminRoleService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.vo.RespBean;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author 小红
 * @since 2022-09-02
 */
@Service
public class AdminRoleServiceImpl extends ServiceImpl<AdminRoleMapper, AdminRole> implements IAdminRoleService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RespBean editAdminRoles(Integer adminId, Integer[] rids) {

        /**
         * 事务传播
         * 当一个支持事务的方法（加了@Transactional），调用了另一个也支持事务的方法，就进行了一次事务传播
         *
         */

        boolean remove = remove(new QueryWrapper<AdminRole>().eq("adminId", adminId));

        List<AdminRole> collect = Arrays.asList(rids)
                .stream()
                .map(x -> new AdminRole().setAdminId(adminId).setRid(x))
                .collect(Collectors.toList());

        boolean saveBatch = saveBatch(collect);
        if (saveBatch && remove) {
            return RespBean.success();
        }else {
            throw RespBean.AUTH_FAILED_ERROR_503.toException();
        }
    }
}
